// app/NewDevice/index.tsx
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, ScrollView, Button, Alert, ActivityIndicator, TextInput } from 'react-native';
import { Stack, useRouter, useLocalSearchParams } from 'expo-router';
import DeviceControl from '@/components/common/DeviceControl';
import { deviceParameters, DEVICE_TYPES, DeviceParam } from '@/constants/deviceParameters';
import ButtonDemo from '@/components/features/device/ButtonDemo';

// 导入 API 接口
import {
  createDevice,
  DeviceData,
} from '@/api/device';

// 定义本地设备状态的类型，键是字符串，值是任意类型
type LocalDeviceState = { [key: string]: any };

export default function NewDevicePage() {
  const router = useRouter();
  const params = useLocalSearchParams();
  // // 读取 deviceType 参数（可能为 undefined）
  // const initialType = (params.deviceType as DEVICE_TYPES) || DEVICE_TYPES.AC;
  
  // 设备基本信息
  const [deviceName, setDeviceName] = useState<string>('');
  const [currentDeviceType, setCurrentDeviceType] = useState<DEVICE_TYPES>(DEVICE_TYPES.AC);
  const [familyId] = useState<string>(''); // 如果需要的话
  
  // 获取当前设备类型的所有参数定义
  const paramsConfig: DeviceParam[] = deviceParameters[currentDeviceType] || [];

  // 使用一个状态对象来存储所有参数的初始值
  const [currentDeviceState, setCurrentDeviceState] = useState<LocalDeviceState>({});
  
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 错误信息
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (params.deviceType && params.deviceType !== currentDeviceType) {
      setCurrentDeviceType(params.deviceType as DEVICE_TYPES);
    }
  }, [params.deviceType]);

  // 初始化设备状态（基于前端配置的默认值）
  useEffect(() => {
    const initialState: LocalDeviceState = {};
    paramsConfig.forEach(param => {
      initialState[param.id] = param.initialValue;
    });
    setCurrentDeviceState(initialState);
  }, [currentDeviceType]); // 当设备类型改变时重新初始化

  // 当某个参数的值改变时调用的函数
  const handleValueChange = (paramId: string, newValue: any) => {
    setCurrentDeviceState(prevState => ({
      ...prevState,
      [paramId]: newValue,
    }));
  };

  // 设备类型改变处理函数
  const handleDeviceTypeChange = (newType: DEVICE_TYPES) => {
    setCurrentDeviceType(newType);
    // 重置设备状态到新类型的默认值
    const newParamsConfig = deviceParameters[newType] || [];
    const newInitialState: LocalDeviceState = {};
    newParamsConfig.forEach(param => {
      newInitialState[param.id] = param.initialValue;
    });
    setCurrentDeviceState(newInitialState);
  };

  // --- 创建新设备 ---
  const handleCreate = async () => {
    // 验证输入
    if (!deviceName.trim()) {
      Alert.alert('验证失败', '请输入设备名称');
      return;
    }

    setLoading(true);
    setError(null);
    
    try {
      // 准备要发送到后端的设备数据
      const deviceData: DeviceData = {
        name: deviceName.trim(),
        type_id: getDeviceTypeId(currentDeviceType), // 需要将设备类型转换为对应的ID
        family_id: familyId || 'default', // 如果有家庭ID概念的话
        meta: {
          device_type: currentDeviceType, // 可以在meta中保存设备类型信息
        },
        // state: { ...currentDeviceState }, // 设备的初始状态
      };

      console.log('正在创建新设备:', deviceData);
      
      // 调用 createDevice API 创建设备
      const response = await createDevice(deviceData);
      
      if (response.data.ok) {
        alert('创建成功');
        router.back(); // 返回到设备列表页面
      } else {
        // API 响应失败，显示错误信息
        setError(response.data.error?.message || '创建设备失败');
        Alert.alert('创建失败', response.data.error?.message || '未知错误');
      }
    } catch (err: any) {
      // 网络错误或其他异常
      setError(err.message || '创建设备网络错误');
      Alert.alert('创建失败', err.message || '网络错误');
      console.error("创建设备失败:", err);
    } finally {
      setLoading(false);
    }
  };

  // 取消创建
  const handleCancel = () => {
    Alert.alert(
      '确认取消',
      '确定要取消创建设备吗？已输入的信息将丢失。',
      [
        { text: '继续编辑', style: 'cancel' },
        { 
          text: '确定取消', 
          style: 'destructive',
          onPress: () => router.push('../(tabs)/DevicePage'),
        }
      ]
    );
  };

  // 将设备类型枚举转换为对应的数字ID（根据你的后端API要求调整）
const getDeviceTypeId = (deviceType: DEVICE_TYPES): number => {
  switch (deviceType) {
    case DEVICE_TYPES.DOOR_LOCK:
      return 1; // smart_lock_with_cat_eye
    case DEVICE_TYPES.CAMERA:
      return 2; // camera
    case DEVICE_TYPES.LIGHT:
      return 3; // light
    case DEVICE_TYPES.AC:
      return 4; // air_conditioner
    case DEVICE_TYPES.AIR_PURIFIER:
      return 5; // air_purifier
    case DEVICE_TYPES.HUMIDIFIER:
      return 6; // humidifier
    case DEVICE_TYPES.CURTAIN:
      return 7; // curtain
    case DEVICE_TYPES.WASHING_MACHINE:
      return 8; // washing_machine
    case DEVICE_TYPES.VACUUM_ROBOT:
      return 9; // vacuum_robot
    case DEVICE_TYPES.REFRIGERATOR:
      return 10; // refrigerator
    case DEVICE_TYPES.DISHWASHER:
      return 11; // dishwasher
    case DEVICE_TYPES.WATER_HEATER:
      return 12; // water_heater
    case DEVICE_TYPES.EXHAUST_FAN:
      return 13; // exhaust_fan
    case DEVICE_TYPES.SMART_TV:
      return 14; // smart_tv
    case DEVICE_TYPES.SMART_SPEAKER:
      return 15; // smart_speaker
    case DEVICE_TYPES.TEMP_HUMIDITY_SENSOR:
      return 16; // temp_humidity_sensor
    case DEVICE_TYPES.MOTION_SENSOR:
      return 17; // motion_sensor
    case DEVICE_TYPES.SMOKE_CO_ALARM:
      return 18; // smoke_co_alarm
    default:
      return 4; // 默认返回空调（air_conditioner）
  }
};
  // 获取设备类型选项（简单的实现，实际项目中可能需要更复杂的UI）
  const deviceTypeOptions = Object.values(DEVICE_TYPES);

  return (
    <ScrollView style={styles.container}>
      {/* 设置页面顶部的标题 */}
      <Stack.Screen options={{ headerShown: false }} />

      {/* 页面主标题 */}
      <View style={styles.header}>
        <Text style={styles.mainTitle}>
          {currentDeviceType}
        </Text>
        <Text style={styles.subTitle}>为设备配置基本信息和初始参数</Text>
      </View>


      {/* 错误信息显示 */}
      {error && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

      {/* 基本信息区域 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>基本信息</Text>
        
        {/* 设备名称输入 */}
        <View style={styles.inputGroup}>
          <Text style={styles.inputLabel}>设备名称 *</Text>
          <TextInput
            style={styles.textInput}
            placeholder="请输入设备名称"
            value={deviceName}
            onChangeText={setDeviceName}
            maxLength={50}
          />
        </View>

        {/* 设备类型选择
        <View style={styles.inputGroup}>
          <Text style={styles.inputLabel}>设备类型</Text>
          <View style={styles.typeButtonContainer}>
            {deviceTypeOptions.map((type) => (
              <View key={type} style={styles.typeButtonWrapper}>
                <Button
                  title={type}
                  onPress={() => handleDeviceTypeChange(type)}
                  color={currentDeviceType === type ? '#007AFF' : '#8E8E93'}
                />
              </View>
            ))}
          </View>
          <Text style={styles.selectedType}>当前选择: {currentDeviceType}</Text>
        </View> */}
      </View>

      {/* 初始参数配置区域 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>初始参数配置</Text>
        <Text style={styles.sectionDescription}>
          设置设备创建后的初始状态，后续可以在设备详情页面中修改
        </Text>

        {/* 动态渲染设备控制项 */}
        {paramsConfig.length > 0 ? (
          paramsConfig.map((param: DeviceParam) => (
            <DeviceControl
              key={param.id}
              param={param}
              value={currentDeviceState[param.id]}
              onValueChange={handleValueChange}
            />
          ))
        ) : (
          <Text style={styles.noParamsText}>该设备类型暂无可配置参数</Text>
        )}
      </View>

      {/* 底部按钮 */}
      <View style={styles.footer}>
        <ButtonDemo 
          text="创建新设备"
          onPress={handleCreate} 
        />
      </View>

      {/* 加载遮罩 */}
      {loading && (
        <View style={styles.overlayLoading}>
          <ActivityIndicator size="large" color="#007AFF" />
          <Text style={styles.loadingText}>正在创建设备...</Text>
        </View>
      )}
      <View style={{paddingBottom: 60}}></View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    paddingTop: 60,
    paddingBottom: 60,
  },
  header: {
    padding: 20,
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  mainTitle: {
    fontSize: 28,
    fontWeight: 'bold',
  },
  subTitle: {
    fontSize: 14,
    color: '#888',
    marginTop: 8,
    textAlign: 'center',
  },
  section: {
    marginTop: 12,
    backgroundColor: '#fff',
    padding: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 15,
  },
  sectionDescription: {
    fontSize: 14,
    color: '#666',
    marginBottom: 15,
  },
  inputGroup: {
    marginBottom: 15,
  },
  inputLabel: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 8,
    color: '#333',
  },
  textInput: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 16,
    backgroundColor: '#fff',
  },
  typeButtonContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 8,
    gap: 8,
  },
  typeButtonWrapper: {
    minWidth: 80,
  },
  selectedType: {
    fontSize: 14,
    color: '#007AFF',
    fontWeight: '500',
  },
  noParamsText: {
    fontSize: 14,
    color: '#888',
    fontStyle: 'italic',
    textAlign: 'center',
    paddingVertical: 20,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 20,
    marginTop: 20,
    marginBottom: 30,
  },
  errorContainer: {
    backgroundColor: '#ffebee',
    margin: 12,
    padding: 12,
    borderRadius: 8,
    borderLeftWidth: 4,
    borderLeftColor: '#f44336',
  },
  errorText: {
    color: '#c62828',
    fontSize: 14,
  },
  overlayLoading: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: '#007AFF',
  },
});